package com.lv.common.widget

import android.content.Context
import android.content.res.TypedArray
import android.util.AttributeSet
import androidx.annotation.NonNull
import androidx.annotation.Nullable
import androidx.core.widget.NestedScrollView
import com.lv.common.R

/**
 * 作者： ygx
 * 创建日期：2023/3/18 3:37 PM
 * 签名： 天行健，君子以自强不息；地势坤，君子以厚德载物。
 * -    _              _           _     _   ____  _             _ _
 * -   / \   _ __   __| |_ __ ___ (_) __| | / ___|| |_ _   _  __| (_) ___
 * -  / _ \ | '_ \ / _` | '__/ _ \| |/ _` | \___ \| __| | | |/ _` | |/ _ \
 * - / ___ \| | | | (_| | | | (_) | | (_| |  ___) | |_| |_| | (_| | | (_) |
 * -/_/   \_\_| |_|\__,_|_|  \___/|_|\__,_| |____/ \__|\__,_|\__,_|_|\___/
 * <p>
 * You never know what you can do until you try !
 * ----------------------------------------------------------------
 * 描述：
 */
class MaxHeightNestedScrollView(
    @NonNull context: Context,
    @Nullable attrs: AttributeSet?,
    defStyleAttr: Int
) :
    NestedScrollView(context, attrs, defStyleAttr) {
    private var maxHeight = -1

    constructor(@NonNull context: Context) : this(context, null, 0) // Modified changes
    {
    }

    constructor(@NonNull context: Context, @Nullable attrs: AttributeSet?) : this(
        context,
        attrs,
        0
    ) // Modified changes
    {
    }

    init {
        init(context, attrs, defStyleAttr) // Modified changes
    }

    // Modified changes
    private fun init(@NonNull context: Context, @Nullable attrs: AttributeSet?, defStyleAttr: Int) {
        val a: TypedArray = context.obtainStyledAttributes(
            attrs, R.styleable.MaxHeightNestedScrollView, defStyleAttr, 0
        )
        maxHeight = a.getDimensionPixelSize(R.styleable.MaxHeightNestedScrollView_maxHeight, 0)
        a.recycle()
    }

    fun getMaxHeight(): Int {
        return maxHeight
    }

    fun setMaxHeight(maxHeight: Int) {
        this.maxHeight = maxHeight
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        var heightMeasureSpec = heightMeasureSpec
        if (maxHeight > 0) {
            heightMeasureSpec = MeasureSpec.makeMeasureSpec(maxHeight, MeasureSpec.AT_MOST)
        }
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
    }
}